<template>
  <div>
    <a-form-model
      ref="createClient"
      :model="client"
      :rules="clientRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :hideRequiredMark="true"
    >
      <div class="flex justify-end" v-if="approve != 2">
        <a-button
          type="primary"
          v-if="(!!client.id || !!lawyer.id || !!surety[0].id) && readOnly"
          @click="readOnly = false"
          v-action:update
        >
          修改
        </a-button>
        <a-button
          v-if="(!!client.id || !!lawyer.id || !!surety[0].id) && !readOnly"
          type="primary"
          @click="updata"
          v-action:update
        >
          保存
        </a-button>
      </div>
      <p class="info">客户信息</p>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="类型：" prop="userType">
            <a-radio-group v-model="client.userType" :disabled="readOnly && client.id ? true : false">
              <a-radio :value="item.value" v-for="item in userType" :key="item.text">
                {{ item.text }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="名称：" prop="name">
            <a-input v-model="client.name" :disabled="readOnly && client.id ? true : false" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row v-if="client.userType == 1">
        <a-col :span="12">
          <a-form-model-item label="企业代码：" prop="companyCode">
            <a-input v-model="client.companyCode" :disabled="readOnly && client.id ? true : false" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="企业电话号码：" prop="phone">
            <a-input v-model="client.phone" :disabled="readOnly && client.id ? true : false">
              <a-select slot="addonBefore" v-model="client.areaCode" :disabled="readOnly && client.id ? true : false">
                <a-select-option :value="item.value" v-for="item in area" :key="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="联络人：" prop="contactPerson">
            <a-input v-model="client.contactPerson" :disabled="readOnly && client.id ? true : false">
              <a-select
                slot="addonAfter"
                v-model="client.contactPersonSex"
                :disabled="readOnly && client.id ? true : false"
              >
                <a-select-option :value="item.value" v-for="item in sex" :key="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="电子邮件：" prop="email">
            <a-input v-model="client.email" :disabled="readOnly && client.id ? true : false" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row v-if="client.userType == 2">
        <a-col :span="12">
          <a-form-model-item label="个人号码：" prop="phone">
            <a-input v-model="client.phone" :disabled="readOnly && client.id ? true : false">
              <a-select slot="addonBefore" v-model="client.areaCode" :disabled="readOnly && client.id ? true : false">
                <a-select-option :value="item.value" v-for="item in area" :key="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="护照/身份证号码：" prop="IdNumber">
            <a-input v-model="client.IdNumber" :disabled="readOnly && client.id ? true : false">
              <a-select slot="addonBefore" v-model="client.IdType" :disabled="readOnly && client.id ? true : false">
                <a-select-option
                  :value="item.value"
                  v-for="item in IDType"
                  :key="item.text"
                  :disabled="readOnly && client.id ? true : false"
                >
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="联络地址：" prop="contactAddress">
            <a-input v-model="client.contactAddress" :disabled="readOnly && client.id ? true : false" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="简介：" prop="intro">
            <a-textarea
              class="text"
              v-model="client.intro"
              :rows="4"
              :disabled="readOnly && client.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="过往建筑经验：" prop="architectureUndergo">
            <a-textarea
              class="text"
              v-model="client.architectureUndergo"
              :rows="4"
              :disabled="readOnly && client.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <p class="info">担保人信息</p>
    <a-button type="primary" class="add" @click="addGuarantee" v-if="approve != 2">新增担保人</a-button>
    <a-form-model
      ref="createSurety"
      :model="suretyform"
      :rules="suretyRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      v-for="(suretyform, i) in surety"
      :key="i"
      class="box"
      :hideRequiredMark="true"
    >
      <h1>担保人{{ i + 1 }}</h1>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="名称:" prop="name">
            <a-input v-model="suretyform.name" :disabled="readOnly && suretyform.id ? true : false" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="电子邮件：" prop="email">
            <a-input v-model="suretyform.email" ref="email" :disabled="readOnly && suretyform.id ? true : false" />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="电话号码：" prop="phone">
            <a-input v-model="suretyform.phone" ref="phone" :disabled="readOnly && suretyform.id ? true : false">
              <a-select
                slot="addonBefore"
                v-model="suretyform.areaCode"
                :disabled="readOnly && suretyform.id ? true : false"
              >
                <a-select-option :value="item.value" v-for="item in area" :key="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="简介：" prop="intro">
            <a-textarea
              class="text"
              v-model="suretyform.intro"
              :rows="4"
              :disabled="readOnly && suretyform.id ? true : false"
            />
          </a-form-model-item>
        </a-col>
        <a-button class="ml-96 mt-20" type="primary" v-if="i != 0" @click="remove(i)">删除</a-button>
      </a-row>
    </a-form-model>
    <a-form-model
      ref="createLawyer"
      :model="lawyer"
      :rules="lawyerRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :hideRequiredMark="true"
    >
      <p class="info">律师信息</p>
      <a-row>
        <a-col :span="12">
          <a-form-model-item label="律师行名称：" prop="name">
            <a-input v-model="lawyer.name" :disabled="readOnly && lawyer.id ? true : false" />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-button
        v-if="!(client.id && lawyer.id && surety[0].id) ? true : false"
        class="space"
        type="primary"
        @click="onSubmit"
      >
        下一步
      </a-button>
    </a-form-model>
  </div>
</template>

<script>
import { userType, sex, area, IDType } from '@/dict'
import {
  createUserClient,
  createUserSurety,
  createUserLawyer,
  getUserClient,
  getUserSurety,
  getUserLawyer,
  updateUserClientById,
  updateUserSuretyById,
  updateUserLawyerById,
  deleteUserSurety,
  createHistory,
  getDetailList
} from '@/api/common'
import { emailRule, commonRule, phoneRule } from '@/utils/rules'
export default {
  name: 'Customer',
  data() {
    return {
      labelCol: { span: 5 },
      wrapperCol: { span: 16 },
      value: 1,
      userType,
      sex,
      // Archive: 0,
      area,
      IDType,
      page: '3',
      readOnly: true,
      client: {
        userType: 1,
        name: '',
        companyCode: '',
        phone: '',
        areaCode: '+64',
        contactPerson: '',
        contactPersonSex: 1,
        email: '',
        IdNumber: '',
        IdType: 1,
        contactAddress: '',
        intro: '',
        architectureUndergo: ''
      },
      clientRules: {
        userType: commonRule,
        name: commonRule,
        companyCode: commonRule,
        phone: phoneRule,
        contactPerson: commonRule,
        email: emailRule,
        IdNumber: commonRule,
        contactAddress: commonRule,
        contactAddress: commonRule,
        intro: commonRule,
        architectureUndergo: commonRule
      },
      surety: [
        {
          name: '',
          phone: '',
          email: '',
          areaCode: '+64',
          intro: ''
        }
      ],
      suretyRules: {
        name: commonRule,
        phone: phoneRule,
        email: emailRule,
        intro: commonRule
      },
      lawyer: {
        name: ''
      },
      lawyerRules: {
        name: commonRule
      }
    }
  },
  watch: {
    client: {
      handler(v) {
        let id = this.$route.query.id
        this.$store.commit('form/SAVE_DATA', {
          key: 'business/client-' + id,
          value: this.client
        })
      },
      deep: true
    },
    surety: {
      handler(v) {
        let id = this.$route.query.id
        this.$store.commit('form/SAVE_DATA', {
          key: 'business/surety-' + id,
          value: this.surety
        })
      },
      deep: true
    },
    lawyer: {
      handler(v) {
        let id = this.$route.query.id
        this.$store.commit('form/SAVE_DATA', {
          key: 'business/lawyer-' + id,
          value: this.lawyer
        })
      },
      deep: true
    }
  },
  mounted() {
    let id = this.$route.query.id
    if (id) {
      this.getClient()
      this.getLaywer()
      this.getSurety()
      // this.getData()
    }
    if (!this.client.id) {
      const formClient = this.$store.state.form?.['business/client-' + id]
      formClient && Object.assign(this.client, formClient)
      const formLaywer = this.$store.state.form?.['business/lawyer-' + id]
      formLaywer && Object.assign(this.lawyer, formClient)
      const formSurety = this.$store.state.form?.['business/surety-' + id]
      formSurety && Object.assign(this.surety, formSurety)
    }
  },
  computed: {
    approve() {
      return Number(this.$route.query.approve)
    }
  },
  methods: {
    // async getData() {
    // const id = this.$route.query.id
    // const res = await getDetailList(id)
    // this.Archive = res.result.data.Archive
    // },
    async getClient() {
      let id = this.$route.query.id
      const res = await getUserClient(id)
      let data = res.result.data
      if (data?.[0]) {
        let form = Object.assign(data?.[0] || {})
        form.IdType = form.IdType == 0 ? 1 : form.IdType
        Object.assign(this.client, form)
      }
    },
    async getLaywer() {
      let id = this.$route.query.id
      const res = await getUserLawyer(id)
      let data = res.result.data
      if (data?.[0]) {
        let form = Object.assign(data?.[0] || {})
        Object.assign(this.lawyer, form)
      }
    },
    async getSurety() {
      let id = this.$route.query.id
      let res = await getUserSurety(id)
      let data = res.result.data

      if (data.length) {
        this.surety = data
      }
    },
    addGuarantee() {
      this.surety.push({
        name: '',
        phone: '',
        email: '',
        areaCode: '+64',
        intro: ''
      })
    },
    remove(i) {
      console.log(this.surety[i])
      if (this.surety[i].id) {
        const id = this.surety[i].id
        deleteUserSurety(id)
      }
      this.surety.splice(i, 1)
    },
    async onSubmit() {
      let projectId = this.$route.query.id
      let valid = false
      this.$refs.createClient.validate(v => (valid = v))
      if (valid) {
        if (this.client.id) {
          var id = this.client.id
          let form = Object.assign({ id }, this.client)
          updateUserClientById(this.client.id, form)
        } else {
          projectId = Number(projectId)
          let form = Object.assign({ projectId }, this.client)
          createUserClient(form)
        }
      }
      let suretyValid = false
      this.surety.forEach((el, i) => {
        this.$refs.createSurety?.[i]?.validate(v => (suretyValid = v))
        el.projectId = projectId
      })
      if (suretyValid) {
        var _new = []
        var _surety = []
        this.surety.forEach(el => {
          if (!el.id) {
            _new.push(el)
          } else {
            _surety.push(el)
          }
        })
        // console.log(_new)
        // console.log(this.surety)

        if (_surety.length != 0) {
          // let form = Object.assign({ projectId }, this.surety)
          updateUserSuretyById({ userSuretyList: _surety })
        }
        if (_new.length != 0) {
          // let form = Object.assign({ projectId }, this.surety)
          createUserSurety({ userSuretyList: _new })
        }
      }
      let lawyerValid = false
      this.$refs.createLawyer.validate(v => (lawyerValid = v))
      if (lawyerValid) {
        if (this.lawyer.id) {
          updateUserLawyerById(this.lawyer.id, this.lawyer)
        } else {
          let form = Object.assign({ projectId }, this.lawyer)
          createUserLawyer(form)
        }
      }
      if (valid && suretyValid && lawyerValid) {
        let id = this.$route.query.id
        this.$store.commit('form/CLEAR', 'business/client-' + id)
        this.$store.commit('form/CLEAR', 'business/lawyer-' + id)
        this.$store.commit('form/CLEAR', 'business/surety-' + id)
        this.$emit('submit')
      }
    },
    // async onSubmit() {
    //   let projectId = this.$route.query.id
    //   let valid = false
    //   this.$refs.createClient.validate(v => (valid = v))
    //   if (valid) {
    //     projectId = Number(projectId)
    //     let form = Object.assign({ projectId }, this.client)
    //     createUserClient(form)
    //   }
    //   let suretyValid = false
    //   this.surety.forEach((el, i) => {
    //     this.$refs.createSurety?.[i]?.validate(v => (suretyValid = v))
    //     el.projectId = projectId
    //   })
    //   if (suretyValid) {
    //     var _new = []
    //     this.surety.forEach(el => {
    //       if (!el.id) {
    //         _new.push(el)
    //       }
    //     })
    //     if (_new.length != 0) {
    //       // let form = Object.assign({ projectId }, this.surety)
    //       createUserSurety({ userSuretyList: _new })
    //     }
    //   }
    //   let lawyerValid = false
    //   this.$refs.createLawyer.validate(v => (lawyerValid = v))
    //   if (lawyerValid) {
    //     let form = Object.assign({ projectId }, this.lawyer)
    //     createUserLawyer(form)
    //   }
    //   if (valid && suretyValid && lawyerValid) {
    //     let id = this.$route.query.id
    //     this.$store.commit('form/CLEAR', 'business/client-' + id)
    //     this.$store.commit('form/CLEAR', 'business/lawyer-' + id)
    //     this.$store.commit('form/CLEAR', 'business/surety-' + id)
    //     this.$emit('submit')
    //   }
    // },
    async updata() {
      let projectId = this.$route.query.id
      let valid = false
      this.$refs.createClient.validate(v => (valid = v))
      if (valid) {
        projectId = Number(projectId)
        let form = Object.assign({ projectId }, this.client)
        updateUserClientById(this.client.id, form)
      }
      let suretyValid = false
      this.surety.forEach((el, i) => {
        this.$refs.createSurety?.[i]?.validate(v => (suretyValid = v))
        el.projectId = projectId
      })
      if (suretyValid) {
        var _new = []
        var _surety = []
        this.surety.forEach(el => {
          if (!el.id) {
            _new.push(el)
          } else {
            _surety.push(el)
          }
        })
        if (_surety.length != 0) {
          updateUserSuretyById({ userSuretyList: _surety })
        }
        if (_new.length != 0) {
          createUserSurety({ userSuretyList: _new })
        }
      }
      let lawyerValid = false
      this.$refs.createLawyer.validate(v => (lawyerValid = v))
      if (lawyerValid) {
        updateUserLawyerById(this.lawyer.id, this.lawyer)
      }
      if (valid && suretyValid && lawyerValid) {
        let id = this.$route.query.id
        const history = {
          recordType: 0,
          tableId: Number(id)
        }
        await createHistory(history)
        this.$store.commit('form/CLEAR', 'business/client-' + id)
        this.$store.commit('form/CLEAR', 'business/lawyer-' + id)
        this.$store.commit('form/CLEAR', 'business/surety-' + id)
      }
      this.readOnly = true
    }
  }
}
</script>
<style>
.info {
  border-left: 2px solid #1890ff;
  padding-left: 10px;
  font-size: 25px;
  margin-left: 50px;
}
.add {
  float: right;
  margin-bottom: 10px;
  margin-right: 20px;
}
.box {
  clear: both;
  border: 1px solid rgb(184, 182, 182);
  padding: 15px;
  margin: 25px;
  border-radius: 10px;
}
.text {
  resize: unset;
  vertical-align: top;
}
.space {
  margin-left: 45%;
}
</style>
